import { Form, Input, Tabs, Upload, Icon, Select, Button, message } from "antd";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import Editor from "../Editor";
import styles from "@/global.less"
import answerStyle from "./answerStyle.less";
import jsonDataUtils from "../jsonDataUtils";
import ReferAnswerModal from "@/pages/KnowledgeManagement/Overview/EditingKnowledge/referAnswerModal";
import ReferAnswerShow from "./referAnswerShow";
import UserSession from "@/UserSession";

const cardVo = {
  type:'',
  data:{
    guide:'',
    title:"",
    desc:"",
    imgUrl:"",
    link:"",
    appId:"",
    path:"",
    params:{}
  }
}
class AnswerUtils extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      activeKey:'0',
      answer:{
        isDefault: true,
        content: "",
        id: "",
        question: null,
        slotValues: [],
        userTagIdList: [],
        contentType: '0',    //答案内容类型 0=纯文本类型, 1=富文本类型, 2=跳转卡片 默认为0
        cardVo:JSON.parse(JSON.stringify(cardVo)),
        contentId:undefined
      },
      imgUrl:'',
      txtContent:'',
      richContent:''
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  //设置答案字段
  setAnswers = answer => {
    console.log(answer);
    if(!answer){
      return false
    }

    //跳转卡片类型
    if(answer.contentType == 2 && jsonDataUtils.isJsonString(answer.content)){
      answer.cardVo = JSON.parse(answer.content)
    }
    if(!answer.cardVo){
      answer.cardVo = cardVo
    }
    //为了和tab的key值对应，讲number格式转化为string格式
    answer.contentType = answer.contentType + ''
    this.setState({
      answer,
      activeKey:answer.contentType,
      imgUrl:answer.cardVo && answer.cardVo.data ? answer.cardVo.data.imgUrl : ''
    },() => {
      //类型为跳转卡片时，需form赋值
      if(answer.contentType == 2){
        this.props.form.setFieldsValue({
          guide:answer.cardVo.data.guide,
          title:answer.cardVo.data.title,
          desc:answer.cardVo.data.desc,
          imgUrl:answer.cardVo.data.imgUrl,
          type:answer.cardVo.type,
        })
        if(answer.cardVo.type != 'WEB'){
          setTimeout(() => {
            this.props.form.setFieldsValue({
              appId:answer.cardVo.data.appId,
              path:answer.cardVo.data.path,
              params:answer.cardVo.data.params
            })
          },300)
        }else{
          this.props.form.setFieldsValue({
            link:answer.cardVo.data.link
          })
        }
      }
      if(answer.contentType == 1){
        this.setState({
          richContent:answer.content
        })
      }
      if(answer.contentType == 0){
        this.setState({
          txtContent:answer.content
        })
      }
    })
  }

  //清空且初始化所有字段信息
  clearInitData = () => {
    this.props.form.resetFields()
    this.setState({
      activeKey:'0',
      answer:{
        isDefault: true,
        content: "",
        id: "",
        question: null,
        slotValues: [],
        userTagIdList: [],
        contentType: '0',    //答案内容类型 0=纯文本类型, 1=富文本类型, 2=跳转卡片 默认为0
        cardVo:JSON.parse(JSON.stringify(cardVo)),
        contentId:undefined
      },
      imgUrl:'',
      txtContent:'',
      richContent:''
    })
  }

  /**
   * 切换答案类型时触发
   * @param {*} activeKey 
   */
  changeKey = activeKey => {
    let { answer,richContent } = this.state;
    //若当前答案为引用答案 则不允许切换tab
    if(answer.question){
      return false
    }
    //若当前为富文本，切换时需获取当前富文本内容，保存在richContent中
    if(this.refs['answerContent']){
      richContent = this.refs['answerContent'].getUeditorContent();
    }
    //当前为卡片，切换时需清空content，否则会展示json字符串
    if(answer.contentType == 2){
      // answer.content = ''
    }

    //若切换到纯文本需要去掉html标签
    // if(activeKey == 0){
    //   answer.content = answer.content.replace(/<[^>]+>/g,"")
    // }

    //切换时需同步修改answer中的contentType字段
    answer.contentType = activeKey

    this.setState({
      activeKey,
      answer,
      richContent
    })
  }

  //修改纯文本赋值
  changeContentByTextArea = e => {
    this.setState({
      txtContent : e.target.value
    })
  }

  //跳转卡片字段校验
  validateCardObj = async () => {
    const values = await this.props.form.validateFields(['type','title','guide','imgUrl','desc','link','appId','path','params'])
    const { answer,imgUrl } = this.state;
    if(values.params && !jsonDataUtils.isJsonString(values.params)){
      return{
        flag:false,
        message: formatMessage({ id: 'answerUtils.answerUtils.incorrectParameterFormat' }),
        result:answer
      }
    }
    let cardVo = {
      type:values.type,
      data:{
        guide:values.guide,
        title:values.title,
        desc:values.desc,
        link:values.link,
        appId:values.appId,
        path:values.path,
        params:values.params ? values.params : '',
        imgUrl
      }
    }
    answer.content = JSON.stringify(cardVo)
    delete answer.cardVo
    return {
      flag:true,
      message:'',
      result:answer
    }
  }

  //上传前校验
  beforeUpload = file => {
		let a = file.name.toLowerCase();

		const pig = file.type.indexOf('image/') >= 0;
		const isJPG = file.type;
		const isLt2M = file.size / 1024 / 1024 < 2;

		if (!pig) {
			if (!isLt2M) {
				message.error(formatMessage({ id: 'answerUtils.answerUtils.uploadImageSize' }));
			} else {
				message.error(formatMessage({ id: 'answerUtils.answerUtils.uploadImageFormat' }));
			}
		} else {
			if (!isLt2M) {
				message.error(formatMessage({ id: 'answerUtils.answerUtils.uploadImageSize' }));
			}
		}
		return isJPG && isLt2M && pig;
  }

  //上传图片change事件
  changeFile = file => {
    if (file.file.status === "done") {
			this.setState({
				imgUrl:file.file.response.url
			});
		}
  }

  //获取完整answer
  getAnswerResult = async () => {
    const { answer,txtContent,richContent } = this.state;
    let answerCheck = {
      flag:true,
      message:'',
      result:null
    }

    answer.contentType = parseInt(answer.contentType)

    if(answer.question){
      //引用答案，则只需获取content ，删除跳转卡片辅助字段
      delete answer.cardVo
      answerCheck.result = answer
      return answerCheck
    }

    //非引用答案，则需要按照类型用不同方式获取
    //跳转卡片 需要验证必填项
    if(answer.contentType == 2){
      const cardValue = await this.validateCardObj()
      return cardValue
    }

    //纯文本 txtContent 删除跳转卡片辅助字段
    if(answer.contentType == 0){
      answer.content = txtContent
      if(answer.cardVo){
        delete answer.cardVo
      }
      answerCheck.result = answer
    }

    //富文本 需要获取富文本内容赋值answer的content字段  删除跳转卡片辅助字段
    if(answer.contentType == 1){
      answer.content = this.refs['answerContent'] ? this.refs['answerContent'].getUeditorContent() : '';
      if(answer.cardVo){
        delete answer.cardVo
      }
      answerCheck.result = answer
    }

    if(!answer.content){
      answerCheck.flag = false;
      answerCheck.message = formatMessage({ id: 'answerUtils.answerUtils.answerCannotBeEmpty' });
    }
    return answerCheck
  }

  //打开引用答案选择弹窗
  openRefer = (type) => {
    this.ReferAnswerModal.openModal(type);
  }

  //选择引用答案后，赋值给answer字段
  setReferAnswer = (row, openType) => {
    console.log(row,openType);
    const { answer } = this.state;
    answer.content = row.answer;
    answer.contentId = row.id;
    answer.question = row.question;
    answer.contentType = row.contentType + '';
    if(answer.contentType == 2 && jsonDataUtils.isJsonString(answer.content)){
      answer.cardVo = JSON.parse(answer.content)
    }
    console.log(answer);
    this.setState({
      answer,
      activeKey:answer.contentType,
      imgUrl:answer.contentType == 2 ? answer.cardVo.data.imgUrl : ''
    },() => {
      this.ReferAnswerModal.cancelModal();
    })

  }

  //取消引用 
  removeRefer = () => {
    const { answer } = this.state;
    answer.question = null
    answer.contentId= undefined
    this.setState({
      answer
    },() => {
      if(answer.contentType == 2){
        this.props.form.setFieldsValue({
          guide:answer.cardVo.data.guide,
          title:answer.cardVo.data.title,
          desc:answer.cardVo.data.desc,
          imgUrl:answer.cardVo.data.imgUrl,
          type:answer.cardVo.type,
          link:answer.cardVo.data.link,
        })
        if(answer.cardVo.type != 'WEB'){
          setTimeout(() => {
            this.props.form.setFieldsValue({
              appId:answer.cardVo.data.appId,
              path:answer.cardVo.data.path,
              params:answer.cardVo.data.params
            })
          },300)
        }
      }
      if(answer.contentType == 1){
        this.setState({
          richContent:answer.content
        })
      }
      if(answer.contentType == 0){
        this.setState({
          txtContent:answer.content
        })
      }
    })
    
    
  }

  render(){
    const { activeKey,answer,imgUrl,txtContent,richContent } = this.state;
    const { hasRefer } = this.props;
    const { getFieldDecorator,getFieldValue } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const uploadButton = (
      <div>
        <Icon type='plus' />
        <div className="ant-upload-text">{formatMessage({ id: 'answerUtils.answerUtils.upload' })}</div>
      </div>
    );
    const uploadProps = {
      name:"file",
      action:"/cloud/file/upload",
      listType:"picture-card",
      accept:'image/*',
      className:styles.answerCardUploader,
      showUploadList:false,
      beforeUpload:this.beforeUpload,
      onChange:this.changeFile
    }
    const tabBarExtraContent = hasRefer ? UserSession.isSystemDataKnowledge() ? null : (
      <Button type="link" onClick={() => this.openRefer('noSlot')}>{formatMessage({ id: 'answerUtils.answerUtils.referAnswer' })}</Button>
    ) : ''
    return(
      <div className="qaAnswer">
        <Tabs 
          type="card" 
          activeKey={activeKey} 
          onChange={this.changeKey}
          tabBarExtraContent={tabBarExtraContent}
          tabBarStyle={{marginBottom:0,borderBottom:0}}
        >
          <Tabs.TabPane key={'0'} tab={formatMessage({ id: 'answerUtils.answerUtils.plainText' })}>
            <div style={{border:answer.question ? '0' : '1px solid #D9D9D9'}}>
              {
                answer.question ? (
                  <ReferAnswerShow answer={answer} changeRefer={this.openRefer} removeRefer={this.removeRefer} hasBtn={true} />
                ) : UserSession.isSystemKnowledge() || this.props.disabled ? (
                  <Input.TextArea rows={5} style={{border:0}} placeholder={formatMessage({ id: 'answerUtils.answerUtils.textPlaceholder' })} disabled value={txtContent} onChange={this.changeContentByTextArea} />
                ) : (
                  <Input.TextArea rows={5} style={{border:0}} placeholder={formatMessage({ id: 'answerUtils.answerUtils.textPlaceholder' })} value={txtContent} onChange={this.changeContentByTextArea} />
                )
              }
            </div>
          </Tabs.TabPane>
          <Tabs.TabPane key={'1'} tab={formatMessage({ id: 'answerUtils.answerUtils.richText' })}>
            {
              activeKey == '1' ? 
                answer.question ? (
                  <ReferAnswerShow answer={answer} changeRefer={this.openRefer} removeRefer={this.removeRefer} hasBtn={true} />
                ) : UserSession.isSystemKnowledge() || this.props.disabled ? (
                  <div className={answerStyle.answerShowBox}>
                    <div
                      dangerouslySetInnerHTML={{ __html: richContent }}
                      style={{
                        padding: 20,
                        border: '1px solid #e8e8e8',
                        borderTop: '0px',
                        marginTop: '-16px',
                      }}
                    />
                  </div>
                ) : (
                  <Editor content={richContent} name={`answerContent`} id={`answerContent`} ref={`answerContent`} />
                )
              : ''
            }
          </Tabs.TabPane>
          <Tabs.TabPane key={'2'} tab={formatMessage({ id: 'answerUtils.answerUtils.jumpCard' })}>
            <div style={{border:answer.question ? '0' : '1px solid #D9D9D9',padding:10}}>
              {
                answer.question ? (
                  <ReferAnswerShow answer={answer} changeRefer={this.openRefer} removeRefer={this.removeRefer} hasBtn={true} />
                ) : (
                  <div>
                    <Form.Item label={formatMessage({ id: 'answerUtils.answerUtils.guideWords' })} {...formItemLayout}>
                      {
                        getFieldDecorator('guide')(
                          <Input.TextArea placeholder={formatMessage({ id: 'answerUtils.answerUtils.enterGuideWords' })} disabled={UserSession.isSystemKnowledge() || this.props.disabled} maxLength={2000} autoSize />
                        )
                      }
                    </Form.Item>
                    <Form.Item label={formatMessage({ id: 'answerUtils.answerUtils.cardTitle' })} {...formItemLayout}>
                      {
                        getFieldDecorator('title',{rules: [{ required: activeKey == 2, message: formatMessage({ id: 'answerUtils.answerUtils.cardTitleRequired' }) }]})(
                          <Input.TextArea autoSize placeholder={formatMessage({ id: 'answerUtils.answerUtils.enterCardTitle' })} disabled={UserSession.isSystemKnowledge() || this.props.disabled} maxLength={100} />
                        )
                      }
                    </Form.Item>
                    <Form.Item label={formatMessage({ id: 'answerUtils.answerUtils.cardDescription' })} {...formItemLayout}>
                      {
                        getFieldDecorator('desc')(
                          <Input.TextArea autoSize placeholder={formatMessage({ id: 'answerUtils.answerUtils.enterCardDescription' })} disabled={UserSession.isSystemKnowledge() || this.props.disabled} maxLength={100}/>
                        )
                      }
                    </Form.Item>
                    <Form.Item label={formatMessage({ id: 'answerUtils.answerUtils.cardImage' })} {...formItemLayout}>
                      {
                        getFieldDecorator('imgUrl',{rules: [{ required: activeKey == 2, message: formatMessage({ id: 'answerUtils.answerUtils.uploadCardImage' }) }]})(
                          <Upload {...uploadProps} disabled={UserSession.isSystemKnowledge() || this.props.disabled}>
                            {
                              imgUrl ? <img style={{width:86,height:86}} src={imgUrl} /> : uploadButton
                            }
                          </Upload>
                        )
                      }
                      <div style={{fontSize:12,color:'#AAAAAA',lineHeight:'20px'}}>{formatMessage({ id: 'answerUtils.answerUtils.imageSizeSuggestion' })}</div>
                    </Form.Item>
                    <Form.Item label={formatMessage({ id: 'answerUtils.answerUtils.jumpObject' })} {...formItemLayout}>
                      {
                        getFieldDecorator('type',{initialValue:'WEB',rules: [{ required: activeKey == 2, message: formatMessage({ id: 'answerUtils.answerUtils.jumpObjectRequired' }) }]})(
                          <Select style={{width:200}} disabled={UserSession.isSystemKnowledge() || this.props.disabled}>
                            <Select.Option value={'WEB'}>{formatMessage({ id: 'answerUtils.answerUtils.webPage' })}</Select.Option>
                            <Select.Option value={'APP'}>{formatMessage({ id: 'answerUtils.answerUtils.app' })}</Select.Option>
                            <Select.Option value={'WXAPP'}>{formatMessage({ id: 'answerUtils.answerUtils.wechatMiniProgram' })}</Select.Option>
                            <Select.Option value={'DDAPP'}>{formatMessage({ id: 'answerUtils.answerUtils.dingtalkMiniProgram' })}</Select.Option>
                            <Select.Option value={'FSAPP'}>{formatMessage({ id: 'answerUtils.answerUtils.feishuMiniProgram' })}</Select.Option>
                          </Select>
                        )
                      }
                    </Form.Item>
                    {
                      getFieldValue('type') == 'WEB' ? (
                        <Form.Item label={formatMessage({ id: 'answerUtils.answerUtils.cardLink' })} {...formItemLayout}>
                        {
                          getFieldDecorator('link',{rules: [{ required: getFieldValue('type') === 'WEB' && activeKey == 2, message: formatMessage({ id: 'answerUtils.answerUtils.cardLinkRequired' })}]})(
                            <Input.TextArea autoSize placeholder={formatMessage({ id: 'answerUtils.answerUtils.enterCardLink' })} disabled={UserSession.isSystemKnowledge() || this.props.disabled} maxLength={1000} />
                          )
                        }
                      </Form.Item>
                      ) : ''
                    }
                    {
                      getFieldValue('type') != 'WEB' ? (
                        <div>
                          <Form.Item label='AppId' {...formItemLayout}>
                            {
                              getFieldDecorator('appId')(
                                <Input placeholder={formatMessage({ id: 'answerUtils.answerUtils.enterAppId' })} disabled={UserSession.isSystemKnowledge() || this.props.disabled} maxLength={1000} />
                              )
                            }
                          </Form.Item>
                          <Form.Item label='Path' {...formItemLayout}>
                            {
                              getFieldDecorator('path')(
                                <Input placeholder={formatMessage({ id: 'answerUtils.answerUtils.enterPath' })} disabled={UserSession.isSystemKnowledge() || this.props.disabled} maxLength={1000} />
                              )
                            }
                          </Form.Item>
                          <Form.Item label={formatMessage({ id: 'answerUtils.answerUtils.carryParameters' })} {...formItemLayout}>
                            {
                              getFieldDecorator('params')(
                                <Input placeholder={formatMessage({ id: 'answerUtils.answerUtils.enterCarryParameters' })} disabled={UserSession.isSystemKnowledge() || this.props.disabled} maxLength={1000} />
                              )
                            }
                          </Form.Item>
                        </div>
                      ):''
                    }
                  </div>
                )
              }
            </div>
          </Tabs.TabPane>
        </Tabs>

        <ReferAnswerModal
					onRef={(ref) => (this.ReferAnswerModal = ref)}
					setReferAnswer={this.setReferAnswer}
				/>
      </div>
    )
  }
}

export default AnswerUtils